<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>DeepSeek 聊天</title>
    <script src="/static/js/vue.js"></script>
    <script src="/static/js/axios.min.js"></script>
    <link rel="stylesheet" href="/static/plugins/fontawesome-free-6.4.0-web/css/all.min.css">
    <link rel="stylesheet" href="/static/css/base.css">
</head>

<body>
    <div id="app" class="container">
        <!-- 未登录状态 - Vue语法区域 -->
        <div v-if="!isAuthenticated" class="auth-container">
            <div class="tabs">
                <div class="tab" :class="{ active: isLoginMode }" @click="isLoginMode = true">登录</div>
                <div class="tab" :class="{ active: !isLoginMode }" @click="isLoginMode = false">注册</div>
            </div>

            <div v-if="error" class="error-message">
                <i class="fas fa-exclamation-triangle"></i> [[ error ]]
            </div>

            <div v-if="successMessage" class="success-message">
                <i class="fas fa-check-circle"></i> [[ successMessage ]]
            </div>

            <form @submit.prevent="isLoginMode ? login() : register()">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" v-model="username" required>
                </div>

                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" v-model="password" required>
                </div>

                <div class="form-group" v-if="!isLoginMode">
                    <label for="email">邮箱（可选）</label>
                    <input type="email" id="email" v-model="email">
                </div>

                <button type="submit" class="auth-button">
                    [[ isLoginMode ? '登录' : '注册' ]]
                </button>
            </form>
        </div>

        <!-- 已登录状态 - Vue语法区域 -->
        <div v-else>
            <!-- 侧边栏 -->
            <div class="sidebar">
                <div class="sidebar-header">菜单</div>
                <div class="sidebar-menu">
                    <div class="sidebar-item" :class="{ active: activeView === 'chat' }" @click="activeView = 'chat'">
                        <i class="fas fa-comments"></i> 聊天
                    </div>
                    <div class="sidebar-item" :class="{ active: activeView === 'api-keys' }"
                        @click="activeView = 'api-keys'">
                        <i class="fas fa-key"></i> API Key管理
                    </div>
                    <div class="sidebar-item" v-if="currentUser.is_admin" :class="{ active: activeView === 'admin' }"
                        @click="activeView = 'admin'">
                        <i class="fas fa-user-shield"></i> 管理员面板
                    </div>
                    <div class="sidebar-item" @click="logout">
                        <i class="fas fa-sign-out-alt"></i> 退出登录
                    </div>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="main-content">
                <!-- 聊天视图 -->
                <div v-if="activeView === 'chat'" class="chat-container">
                    <div class="chat-header">
                        <h1><i class="fas fa-robot"></i> DeepSeek 聊天</h1>
                        <div class="user-info">
                            <span>[[ currentUser.username ]]</span>
                            <span v-if="currentUser.is_admin" class="admin-badge">管理员</span>
                        </div>
                    </div>

                    <div class="chat-messages">
                        <div v-for="(msg, index) in messages" :key="index"
                            :class="['message', msg.role === 'user' ? 'user-message' : 'assistant-message']">
                            <div class="message-meta">[[ msg.role === 'user' ? '你' : 'DeepSeek' ]]</div>
                            <div class="message-content">[[ msg.content ]]</div>
                        </div>

                        <div v-if="isTyping" class="typing-indicator">
                            <i class="fas fa-circle-notch fa-spin"></i> 正在思考...
                        </div>

                        <div v-if="error" class="error-message">
                            <i class="fas fa-exclamation-triangle"></i> [[ error ]]
                        </div>
                    </div>

                    <div class="history-controls">
                        <button class="history-btn" @click="clearHistory">
                            <i class="fas fa-trash"></i> 清空历史
                        </button>
                    </div>

                    <div class="chat-input">
                        <input type="text" id="message-input" v-model="newMessage" placeholder="输入消息..."
                            @keyup.enter="sendMessage">
                        <button class="send-btn" @click="sendMessage">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </div>

                <!-- API Key管理视图 -->
                <div v-if="activeView === 'api-keys'">
                    <div class="chat-header">
                        <h1><i class="fas fa-key"></i> API Key管理</h1>
                    </div>

                    <div class="api-keys-container">
                        <div class="section-header">
                            <h2>我的API Key</h2>
                            <button class="btn btn-primary" @click="createNewAPIKey">
                                <i class="fas fa-plus"></i> 申请新Key
                            </button>
                        </div>

                        <div v-if="apiKeys.length === 0" class="status-indicator">
                            暂无API Key，请点击上方按钮申请
                        </div>

                        <div v-for="key in apiKeys" :key="key.id" class="api-key-card" :class="{
                            'pending': !key.is_active && !key.is_revoked,
                            'active': key.is_active && !key.is_revoked,
                            'revoked': key.is_revoked
                        }">
                            <div class="api-key-header">
                                <div>
                                    <strong>[[ key.description ]]</strong>
                                    <div v-if="!key.is_active && !key.is_revoked" class="badge pending">待审核</div>
                                    <div v-if="key.is_active && !key.is_revoked" class="badge active">已激活</div>
                                    <div v-if="key.is_revoked" class="badge revoked">已吊销</div>
                                </div>
                                <div class="api-key-actions">
                                    <button class="btn btn-outline" @click="copyToClipboard(key.key)"
                                        v-if="key.is_active && !key.is_revoked">
                                        <i class="fas fa-copy"></i> 复制
                                    </button>
                                </div>
                            </div>

                            <div class="key-display">
                                [[ key.key ]]
                            </div>

                            <div class="key-meta">
                                创建时间: [[ formatDate(key.created_at) ]]
                                <span v-if="key.activated_at">, 激活时间: [[ formatDate(key.activated_at) ]]</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 管理员视图 -->
                <div v-if="activeView === 'admin' && currentUser.is_admin">
                    <div class="chat-header">
                        <h1><i class="fas fa-user-shield"></i> 管理员面板</h1>
                    </div>

                    <div class="admin-section">
                        <div class="section-header">
                            <h2>用户管理</h2>
                        </div>

                        <table class="user-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>邮箱</th>
                                    <th>注册时间</th>
                                    <th>角色</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="user in allUsers" :key="user.id">
                                    <td>[[ user.id ]]</td>
                                    <td>[[ user.username ]]</td>
                                    <td>[[ user.email || '-' ]]</td>
                                    <td>[[ formatDate(user.created_at) ]]</td>
                                    <td>[[ user.is_admin ? '管理员' : '普通用户' ]]</td>
                                </tr>
                            </tbody>
                        </table>

                        <div class="section-header" style="margin-top: 2rem;">
                            <h2>待激活API Key</h2>
                        </div>

                        <table class="api-key-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户</th>
                                    <th>描述</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="key in pendingAPIKeys" :key="key.id">
                                    <td>[[ key.id ]]</td>
                                    <td>[[ key.username ]]</td>
                                    <td>[[ key.description ]]</td>
                                    <td>[[ formatDate(key.created_at) ]]</td>
                                    <td>
                                        <button class="btn btn-success" @click="activateAPIKey(key.id)">
                                            <i class="fas fa-check"></i> 激活
                                        </button>
                                        <button class="btn btn-danger" @click="revokeAPIKey(key.id)">
                                            <i class="fas fa-times"></i> 拒绝
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, onMounted, watch, reactive, toRefs, computed } = Vue;

        // 1. 创建Vue应用实例
        const app = createApp({
            setup() {
                // 状态管理
                const state = reactive({
                    // 认证相关
                    isAuthenticated: false,
                    isLoginMode: true,
                    username: '',
                    password: '',
                    email: '',
                    currentUser: null,
                    token: localStorage.getItem('token') || null,

                    // 视图相关
                    activeView: 'chat', // chat, api-keys, admin

                    // 聊天相关
                    messages: [],
                    newMessage: '',
                    isTyping: false,

                    // API Key相关
                    apiKeys: [],
                    pendingAPIKeys: [],
                    allUsers: [],

                    // 错误和消息
                    error: '',
                    successMessage: '',

                    // API配置
                    API_BASE_URL: ''
                });

                // 设置Axios默认请求头
                const setupAxios = () => {
                    if (state.token) {
                        axios.defaults.headers.common['Authorization'] = `Bearer ${state.token}`;
                    } else {
                        delete axios.defaults.headers.common['Authorization'];
                    }
                };

                // 检查认证状态
                const checkAuth = async () => {
                    if (state.token) {
                        setupAxios();
                        try {
                            // 这里需要后端提供一个获取当前用户信息的接口
                            const response = await axios.get(`${state.API_BASE_URL}/users/me`);
                            state.currentUser = response.data;
                            state.isAuthenticated = true;

                            // 加载必要数据
                            loadChatHistory();
                            loadAPIKeys();

                            // 如果是管理员，加载管理员数据
                            if (state.currentUser.is_admin) {
                                loadAdminData();
                            }
                        } catch (err) {
                            logout();
                        }
                    }
                };

                // 登录
                const login = async () => {
                    try {
                        state.error = '';
                        const response = await axios.post(`${state.API_BASE_URL}/token`, {
                            username: state.username,
                            password: state.password
                        }, {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            transformRequest: [(data) => {
                                let ret = '';
                                for (let it in data) {
                                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                                }
                                return ret;
                            }]
                        });

                        state.token = response.data.access_token;
                        localStorage.setItem('token', state.token);
                        setupAxios();

                        // 获取用户信息
                        const userResponse = await axios.get(`${state.API_BASE_URL}/users/me`);
                        state.currentUser = userResponse.data;
                        state.isAuthenticated = true;
                        state.activeView = 'chat';

                        // 加载数据
                        loadChatHistory();
                        loadAPIKeys();

                        if (state.currentUser.is_admin) {
                            loadAdminData();
                        }

                        // 重置表单
                        state.username = '';
                        state.password = '';
                    } catch (err) {
                        state.error = err.response?.data?.detail || '登录失败，请检查用户名和密码';
                    }
                };

                // 注册
                const register = async () => {
                    try {
                        state.error = '';
                        state.successMessage = '';

                        await axios.post(`${state.API_BASE_URL}/register`, {
                            username: state.username,
                            password: state.password,
                            email: state.email
                        });

                        state.successMessage = '注册成功，请登录';
                        state.isLoginMode = true;

                        // 重置表单
                        state.username = '';
                        state.password = '';
                        state.email = '';
                    } catch (err) {
                        state.error = err.response?.data?.detail || '注册失败';
                    }
                };

                // 退出登录
                const logout = () => {
                    state.token = null;
                    state.currentUser = null;
                    state.isAuthenticated = false;
                    state.messages = [];
                    state.apiKeys = [];
                    state.pendingAPIKeys = [];
                    state.allUsers = [];
                    localStorage.removeItem('token');
                    setupAxios();
                };

                // API Key管理
                const loadAPIKeys = async () => {
                    try {
                        const response = await axios.get(`${state.API_BASE_URL}/api-keys`);
                        state.apiKeys = response.data;
                    } catch (err) {
                        state.error = '加载API Key失败';
                        console.error(err);
                    }
                };

                const createNewAPIKey = async () => {
                    try {
                        const response = await axios.post(`${state.API_BASE_URL}/api-keys`, {
                            description: 'API Key申请'
                        });
                        state.apiKeys.push(response.data);
                        state.successMessage = 'API Key申请已提交，请等待管理员审核';

                        // 3秒后清除成功消息
                        setTimeout(() => {
                            state.successMessage = '';
                        }, 3000);
                    } catch (err) {
                        state.error = '申请API Key失败';
                        console.error(err);
                    }
                };

                // 管理员功能
                const loadAdminData = async () => {
                    try {
                        // 获取所有用户
                        const usersResponse = await axios.get(`${state.API_BASE_URL}/admin/users`);
                        state.allUsers = usersResponse.data;

                        // 获取待激活API Key
                        const keysResponse = await axios.get(`${state.API_BASE_URL}/admin/pending-api-keys`);
                        state.pendingAPIKeys = keysResponse.data;
                    } catch (err) {
                        state.error = '加载管理员数据失败';
                        console.error(err);
                    }
                };

                const activateAPIKey = async (keyId) => {
                    try {
                        await axios.post(`${state.API_BASE_URL}/admin/api-keys/${keyId}/activate`);
                        // 重新加载数据
                        loadAdminData();
                        state.successMessage = 'API Key已激活';

                        setTimeout(() => {
                            state.successMessage = '';
                        }, 3000);
                    } catch (err) {
                        state.error = '激活API Key失败';
                        console.error(err);
                    }
                };

                const revokeAPIKey = async (keyId) => {
                    try {
                        await axios.post(`${state.API_BASE_URL}/admin/api-keys/${keyId}/revoke`);
                        // 重新加载数据
                        loadAdminData();
                        state.successMessage = 'API Key已拒绝';

                        setTimeout(() => {
                            state.successMessage = '';
                        }, 3000);
                    } catch (err) {
                        state.error = '操作失败';
                        console.error(err);
                    }
                };

                // 聊天功能
                const loadChatHistory = async () => {
                    try {
                        state.error = '';
                        const response = await axios.get(`${state.API_BASE_URL}/chat/history`);
                        state.messages = response.data;
                    } catch (err) {
                        state.error = '加载聊天历史失败';
                        console.error(err);
                    }
                };

                const clearHistory = async () => {
                    if (confirm('确定要清空聊天历史吗？')) {
                        try {
                            await axios.delete(`${state.API_BASE_URL}/chat/history`);
                            state.messages = [];
                        } catch (err) {
                            state.error = '清空聊天历史失败';
                            console.error(err);
                        }
                    }
                };

                const sendMessage = async () => {
                    if (!state.newMessage.trim()) return;

                    state.error = '';
                    const userMessage = state.newMessage.trim();

                    // 添加用户消息到本地列表
                    state.messages.push({
                        role: 'user',
                        content: userMessage,
                        id: Date.now()
                    });

                    // 清空输入框
                    state.newMessage = '';

                    // 显示正在输入状态
                    state.isTyping = true;

                    try {
                        // 选择第一个可用的API Key
                        const activeKey = state.apiKeys.find(k => k.is_active && !k.is_revoked);
                        if (!activeKey) {
                            throw new Error('没有可用的API Key，请先申请并等待管理员激活');
                        }

                        // 设置API Key头
                        const headers = {
                            'X-API-Key': activeKey.key
                        };

                        // 发送请求到后端
                        const response = await axios.post(
                            `${state.API_BASE_URL}/chat`,
                            { message: userMessage, api_key_id: activeKey.id },
                            { headers }
                        );

                        // 添加助手消息
                        state.messages.push(response.data);
                    } catch (err) {
                        state.error = err.response?.data?.detail || err.message || '发送消息失败，请重试';
                        console.error(err);
                    } finally {
                        // 隐藏正在输入状态
                        state.isTyping = false;
                        scrollToBottom();
                    }
                };

                // 工具函数
                const scrollToBottom = () => {
                    setTimeout(() => {
                        const chatContainer = document.querySelector('.chat-messages');
                        if (chatContainer) {
                            chatContainer.scrollTop = chatContainer.scrollHeight;
                        }
                    }, 100);
                };

                const copyToClipboard = (text) => {
                    navigator.clipboard.writeText(text).then(() => {
                        state.successMessage = '已复制到剪贴板';
                        setTimeout(() => {
                            state.successMessage = '';
                        }, 2000);
                    }).catch(err => {
                        state.error = '复制失败，请手动复制';
                        console.error('无法复制文本: ', err);
                    });
                };

                const formatDate = (dateString) => {
                    if (!dateString) return '';
                    const date = new Date(dateString);
                    return date.toLocaleString();
                };

                // 初始化
                onMounted(() => {
                    setupAxios();
                    checkAuth();
                });

                // 监听消息变化，自动滚动到底部
                watch(() => state.messages, scrollToBottom);

                return {
                    ...toRefs(state),
                    login,
                    register,
                    logout,
                    sendMessage,
                    clearHistory,
                    loadChatHistory,
                    loadAPIKeys,
                    createNewAPIKey,
                    loadAdminData,
                    activateAPIKey,
                    revokeAPIKey,
                    copyToClipboard,
                    formatDate
                };
            }
        });
        // 4. 配置分隔符（关键：在 mount 前执行，确保生效）
        app.config.compilerOptions.delimiters = ['[[', ']]'];
        // console.log("Vue 分隔符配置：", app.config.delimiters); // 正常应显示 ["[[", "]]"]

        // 5. 挂载应用（最后执行，确保配置已生效）
        app.mount('#app');
        // console.log("Vue 应用是否挂载成功：", document.querySelector('#app').__vue__); // 正常应显示 Vue 实例对象
    </script>
</body>

</html>